#!/usr/bin/perl
#vol_delete.cgi

require './diskman-lib.pl';

&ReadParse();

my ($err_msg, $log_ev, $log_msg, $log_pri);

$err_msg="";
$log_ev="";

my $volname = $in{'volume'};
if (!$volname) {
	$err_msg = $text{"err_cgiparam"};
	goto ERROR_OUT;
}
$uxx = "/c0/".$volname;
my $mkfs_lock;
$mkfs_lock = check_lock();
if ($mkfs_lock) {
        `touch /root/lock`;
	$err_msg = $text{"err_mkfslocked"};
	goto ERROR_OUT;
}
my (@rdinfo, $r, $rr, @lvinfo, @sdinfo, @pvinfo);
@rdinfo = new_get_check_raid_info();
@sdinfo = get_sd_info();
@pvinfo = get_pv_info();
$found = 0;
foreach $r (@rdinfo) {
	if ($r->{'name'} eq $volname) {
		$rr = $r;
		$found = 1;
		last;
	}
}
if (!$found) {
	#finish latter
	$err_msg = $text{"err_configchanged"};
	goto ERROR_OUT;
}


@lvinfo = get_lv_info();

my ($out, $mddev, @rdev);

$volume_name = $rr->{'volname'};
my $pvdev;
foreach $ss (@sdinfo) {
	if ($ss->{'volname'} eq $volume_name){
		$pvdev = $ss->{'name'};
		last;
	}
}
my $pvfound = 0;
my $sdpv;
foreach $pvv (@pvinfo) {
	if($pvv->{'pv'} eq $pvdev) {
		$pvfound = 1;
		$sdpv = $pvv;
		last;
	}
}
if($pvfound){
	if($sdpv->{'vg'}){
		$err_msg = $text{'err_raid_in_vg'};
		goto ERROR_OUT;
	}
	else{
		$out1 = `/sbin/lvm pvremove $pvdev -ff -y 2>/dev/null`;
		$rc1 = $?>>8;
		if(!rc1){
			$err_msg = $text{'err_pvremove'};
			goto ERROR_OUT;
		}		
	}
}

my ($d, $p);
#check whether the status of volume
if ($rr->{'status'} eq 'new') {
	#raid stop
	delete_voltab($volume_name);
}
elsif (($rr->{'status'} eq 'NORMAL') || ($rr->{'status'} eq 'INITIALIZING')) {
        foreach $lv (@lvinfo) {
           if ($lv->{'volname'} eq $rr->{'volname'}) {
               $lvdev = $lv->{'name'};
               $lvpath = '/usrvol/'.$lv->{'volume_name'};
               if(mounton($lvdev, $lvpath)){
                  `umount $lvpath`;
                  if ($?) {
                      $err_msg = $text{"err_volbusy"};
                      goto ERROR_OUT;
                  }
               }
           }
        }
        $uid = $rr->{'name'};
#        system("/sbin/tw_cli/tw_cli $uxx del quiet");
	$tmpcmd = "hptraidconf delete ".$volname." RAID hpt";
	system($tmpcmd);
        if(!$?){
           #write_sdconf_rm_unit($uid);
	   delete_voltab($volume_name);
        }
}
else {  
	$err_msg = $text{"err_configchanged"};
	goto ERROR_OUT;	
}

$log_ev = $text{'log_ev_delvolume_ok'};
$log_msg= &text('log_msg_delvolume_ok', $volname);
nas_syslog($text{'my_log_minor'}, 'naslog_info', $log_ev, $log_msg);
redirect("index.cgi");

ERROR_OUT:
&error_setup($text{'del_err_title'});
&error($err_msg);
